# coding:utf-8
# Author : hiicy redldw
# Date : 2019/01/19
# 截断
import pywt
import numpy as np
import pandas as pd

#截断
def hua(data:pd.Series,q3):
    # print('*'*20)
    final = []
    for index,va in enumerate(data):
        # print(type(va))
        if va > q3:
            final=data[index:]
            break
    # print(final)
    ni = final[::-1]
    j=0
    for index,va in enumerate(ni):
        if va > q3:
            j = (len(final) - index)
            break
    final = final[:j]
    # print(len(final))
    return final
    # print(final)
    # print('#'*20)


# 降采样 1/10
def resample(data:pd.DataFrame):
    # print(len(data))
    sample = []
    for i in range(0,len(data),10):
        sample.append(data.iloc[i,:])
    data = pd.DataFrame(sample)
    # 随机采样
    # data = data.sample(frac=1/10)
    # print(len(data))
    return data


# 小波滤噪
def wavelet_denoising(data):
    # 小波函数取db4
    db4 = pywt.Wavelet('db4')
    if type(data) is not None:
        # 分解
        coeffs = pywt.wavedec(data, db4)
        print(len(coeffs))
        # 高频系数置零
        coeffs[len(coeffs)-1] *= 0
        coeffs[len(coeffs)-2] *= 0
        # 重构
        meta = pywt.waverec(coeffs, db4)
        return meta


# 小波去噪2
def wavelet_denoising2(data):
    # 小波函数 取db8
    wavelet = pywt.Wavelet('db8')
    coeff = pywt.wavedec(data, wavelet, level=4)
    sgn = lambda x: 1 if x > 0 else -1 if x < 0 else 0
    # 去噪,
    for i in range(1, 5):
        cD = coeff[i]
        for j in range(len(cD)):
            Tr = np.sqrt(2 * np.log(len(cD)))  # 计算阈值
            if cD[j] >= Tr:
                coeff[i][j] = sgn(cD[j]) - Tr  # 向零收缩
            else:
                coeff[i][j] = 0  # 低于阈值置零
    denoised_index = pywt.waverec(coeff, 'db8')
    return denoised_index

